package job58;

/**
 * @author tmh
 * @date 2024/10/18 19:55
 * @description
 */
public class T2 {
    public static void main(String[] args) {
        System.out.println(new T2().bitwiseComplement(5));
    }
    /**
     * 代码中的类名、方法名、参数名已经指定，请勿修改，直接返回方法规定的值即可
     *
     *
     * @param n int整型
     * @return int整型
     */
    public int bitwiseComplement (int n) {
        // write code here
        String result = change(n);
        int num  =0;
        int index=1;
        int len = result.length();
        for (int i=len-1;i>=0;i--){
            int temp=result.charAt(i)-'0';
            temp=temp*index;
            index=index*2;
            num+=temp;
        }
        return num;
    }

    private String change(int num){
        StringBuilder builder = new StringBuilder();
        while (num!=0){
            builder.append(num%2);
            num=num/2;
        }
        String result = builder.reverse().toString();
        if (result.contains("0")&&result.contains("1")){
            result=result.replace("0","2");
            result=result.replace("1","0");
            result=result.replace("2","1");
        }else if (result.contains("0")){
            result=result.replace("0","1");
        }else if (result.contains("1")){
            result=result.replace("1","0");
        }
        return result;
    }
}
